package com.zhang.config;

import com.zhang.subscriber.MqttPushClient;
import com.zhang.subscriber.MqttSubClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * 配置类
 * @author wfeil211@foxmail.com
 * @date 2023-2-11 20:11:46
 */
@Component
@Slf4j
@ConfigurationProperties("spring.mqtt")
public class MqttConfig {

    @Autowired
    private MqttPushClient mqttPushClient;

    @Autowired
    private MqttSubClient mqttSubClient;

    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;
    /**
     * 连接地址
     */
    private String hostUrl;
    /**
     * 客户Id
     */
    private String clientId;
    /**
     * 默认连接话题
     */
    private String defaultTopic;
    /**
     * 超时时间
     */
    private int timeout;
    /**
     * 保持连接数
     */
    private int keepalive;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getHostUrl() {
        return hostUrl;
    }

    public void setHostUrl(String hostUrl) {
        this.hostUrl = hostUrl;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getDefaultTopic() {
        return defaultTopic;
    }

    public void setDefaultTopic(String defaultTopic) {
        this.defaultTopic = defaultTopic;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public int getKeepalive() {
        return keepalive;
    }

    public void setKeepalive(int keepalive) {
        this.keepalive = keepalive;
    }

    /**
     * 连接至mqtt服务器，获取mqtt连接
     *
     * @return
     */
    @Bean
    public MqttPushClient getMqttPushClient() {
        //连接至mqtt服务器，获取mqtt连接

        mqttPushClient.connect(hostUrl, clientId, username, password, timeout, keepalive);
        //一连接mqtt,就订阅默认需要订阅的主题（如test_queue）
        mqttSubClient.subScribeDataPublishTopic(defaultTopic);
        log.info("连接成功");
        return mqttPushClient;
    }

}
